package com.andyyan.ai.chatbot.controllers;

import com.alibaba.fastjson.JSONObject;
import com.andyyan.ai.chatbot.model.ApiResult;
import com.andyyan.ai.chatbot.model.Conversation;
import com.andyyan.ai.chatbot.model.PromptParam;
import com.andyyan.ai.chatbot.service.impl.ConversationServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.Objects;

import static com.andyyan.ai.chatbot.constant.ChatBotConstant.USER_ID;

@Slf4j
@RestController
@RequestMapping("/api/ai/conversation")
@RequiredArgsConstructor
public class ConversationController {

    private final ConversationServiceImpl conversationService;
    private final ChatMemory chatMemory;
    private final ChatClient chatClient;

    // 访问页面请求会话列表
    @GetMapping("/list")
    public ApiResult<?> conversationList(@CookieValue(value = USER_ID) String userId) {
        List<Conversation> conversationList = conversationService.userConversationList(userId);
        return ApiResult.success(conversationList);
    }

    @RequestMapping("/create")
    public ApiResult<?> createConversation(@CookieValue(value = USER_ID) String userId) {
        Conversation conversation = conversationService.createConversation(userId);
        if (Objects.isNull(conversation)) {
            log.error("userId:{}, create conversation failed", userId);
            return ApiResult.fail(4, "创建conversation失败", null);
        }
        return ApiResult.success(conversation);
    }

    @RequestMapping("/delete")
    public ApiResult<?> deleteConversation(@CookieValue(value = USER_ID) String userId,
                                      String conversationId) {
        boolean delResult = conversationService.deleteConversation(userId, conversationId);
        return delResult ? ApiResult.success(null) : ApiResult.fail(5, "删除会话失败", null);
    }

    @GetMapping("/msg/list")
    public ApiResult<?> conversationMsgHistory(@CookieValue(value = USER_ID) String userId,
                                          String conversationId) {
        Conversation conversation = conversationService.queryConversation(userId, conversationId);
        if (Objects.isNull(conversation)) {
            ApiResult.fail(6, "conversationId不合法", null);
        }

        List<Message> msgList = chatMemory.get(conversationId);
        return ApiResult.success(msgList);
    }

    @PostMapping(value = "/prompt", produces = "text/html;charset=UTF-8")
    public Flux<String> prompt(@CookieValue(value = USER_ID) String userId,
                               @RequestBody PromptParam promptParam) {
        String conversationId = promptParam.getConversationId();
        String prompt = promptParam.getPrompt();
        // 先查询conversationId 是否存在
        Conversation conversation = conversationService.queryConversation(userId, conversationId);
        if (Objects.isNull(conversation)) {
            return Flux.just(JSONObject.toJSONString(ApiResult.fail(6, "conversationId不合法", null)));
        }

        return chatClient.prompt()
                .user(prompt)
                .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, conversationId))
                .stream()
                .content();
    }
}
